package org.example.bishe1.exception;

import lombok.extern.slf4j.Slf4j;
import org.example.bishe1.pojo.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常: {}", e.getMessage());
        return Result.error("出错了");
    }

    //数据库重复异常
    @ExceptionHandler
    public Result handerDuplicateKeyException(DuplicateKeyException e) {
        log.error("数据库重复异常: {}", e.getMessage());
        String msg = e.getMessage();
        int index =msg.indexOf("Duplicate entry");
        String errMsg = msg.substring(index);
        String[] arr =errMsg.split(" ");
        return Result.error("数据库重复异常: "+arr[2]+"已存在");
    }
}
